package com.lianmai.chaincard.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.lianmai.chaincard.MyApplication;
import com.youth.xframe.cache.XCache;
import com.youth.xframe.utils.XEncryptUtils;

import java.io.IOException;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * app信息
 */
public class AppConfig {
    /**
     * 调式模式开关
     */
    public static boolean DEBUG = false;
    /**
     * 包名
     */
    public static String PACKAGE_NAME;
    /**
     * app内部版本号
     */
    public static int VERSION_CODE;
    /**
     * app外部版本号
     */
    public static String VERSION_STRING;
    /**
     * 设备类型
     */
    public static int DEVICE_TYPE;//2 Android，1 IOS
    /**
     * 设备系统版本
     */
    public static String DEVICE_VER;
    /**
     * 设备型号
     */
    public static String DEVICE_MODEL;
    /**
     * 设备ID
     */
    private static String DEVICE_ID;
    /**
     * 渠道ID
     */
    public static int CHANNEL_ID = 1;

    @SuppressLint("MissingPermission")
    public static String getDeviceId() {
        if (TextUtils.isEmpty(DEVICE_ID)) {
            try {
                TelephonyManager telephonyManager = (TelephonyManager) MyApplication.getInstance().getSystemService(Context.TELEPHONY_SERVICE);
                DEVICE_ID = telephonyManager.getDeviceId();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (TextUtils.isEmpty(DEVICE_ID)) {
                XCache mCache = XCache.get(MyApplication.getInstance());
                String oldDeviceId = mCache.getAsString("device_id");
//                SharedPreferencesUtil spUtil = SharedPreferencesUtil.getMainSharedPreferencesUtil(MyApplication.getInstance());
//                String oldDeviceId = spUtil.getString("device_id", "");
                if (TextUtils.isEmpty(oldDeviceId)) {
                    DEVICE_ID = "chain" + XEncryptUtils.MD5(String.valueOf(System.currentTimeMillis()));
                    mCache.put("device_id", DEVICE_ID);
                } else {
                    DEVICE_ID = oldDeviceId;
                }
            }
        }
        return DEVICE_ID;
    }

    public static void updateDeviceId() {
        try {
            TelephonyManager telephonyManager = (TelephonyManager) MyApplication.getInstance().getSystemService(Context.TELEPHONY_SERVICE);
            @SuppressLint("MissingPermission") String deviceId = telephonyManager.getDeviceId();
            if (!TextUtils.isEmpty(deviceId)) {
                DEVICE_ID = deviceId;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void initVersion(Context context) {
        try {
            PACKAGE_NAME = context.getPackageName();
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            VERSION_STRING = packageInfo.versionName;
            VERSION_CODE = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("MissingPermission")
    private static void initDevice(Context context) {
        DEVICE_TYPE = 2;
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            DEVICE_ID = telephonyManager.getDeviceId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        DEVICE_MODEL = Build.MODEL;
        DEVICE_VER = Build.VERSION.RELEASE;
    }

    private static void initChannel(Context context) {
        XCache mCache = XCache.get(context);
        String oldDeviceId = mCache.getAsString("device_id");
//        SharedPreferencesUtil spUtil = SharedPreferencesUtil.getMainSharedPreferencesUtil(context);
//        int channel = spUtil.getInt("channel_id", 0);
        int channel = Integer.parseInt(mCache.getAsString("channel_id"), 0);
        if (channel > 0) {
            CHANNEL_ID = channel;
            return;
        }
        ApplicationInfo appInfo;
        try {
            appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);
            channel = appInfo.metaData.getInt("CHANNEL_ID", -1);
            if (channel == -1) {
                String channelString = appInfo.metaData.getString("CHANNEL_ID", "");
                channelString = channelString.replaceAll(" ", "");
                Pattern pattern = Pattern.compile("([0-9]+)");
                Matcher matcher = pattern.matcher(channelString);
                if (matcher.find()) {
                    channelString = matcher.group(1);
                }
                try {
                    channel = Integer.parseInt(channelString);
                } catch (Exception e) {
                    channel = 0;
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (channel != 1) {
            appInfo = context.getApplicationInfo();
            String sourceDir = appInfo.sourceDir;
            String ret = "";
            ZipFile zipfile = null;
            try {
                zipfile = new ZipFile(sourceDir);
                Enumeration<?> entries = zipfile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = ((ZipEntry) entries.nextElement());
                    String entryName = entry.getName();
                    if (entryName.contains("channel")) {
                        ret = entryName;
                        break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (zipfile != null) {
                    try {
                        zipfile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            String[] split = ret.split("_");
            if (split.length >= 2) {
                try {
                    channel = Integer.parseInt(ret.substring(split[0].length() + 1), 10);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (channel <= 0) {
            channel = 1;
        }
//        spUtil.put("channel_id", channel);
        mCache.put("channel_id", channel);
        CHANNEL_ID = channel;
    }

    static {
        initVersion(MyApplication.getInstance());
        initDevice(MyApplication.getInstance());
//        initChannel(FBApplication.getInstance());
    }
}
